//
//  TableFooterCell.m
//  TableViewExpand
//
//  Created by Bismarrck on 11-7-17.
//  Copyright 2011年 Tsinghua University. All rights reserved.
//

#import "TableFooterCell.h"

#define BUTTON_NORMAL_TITLE     @"获取更多信息"
#define BUTTON_REFRESH_TITLE    @"正在载入信息"

@interface TableFooterCell ()

- (void)setButtonTitle:(NSString *)buttonTitle;
- (void)setState:(TableFooterState)state;

@end

@implementation TableFooterCell

@synthesize delegate;

- (void)setButtonTitle:(NSString *)buttonTitle
{
    [refreshButton_ setTitle:buttonTitle forState:UIControlStateNormal];
    [refreshButton_ setTitle:buttonTitle forState:UIControlStateHighlighted];
    [refreshButton_ setTitle:buttonTitle forState:UIControlStateSelected];
}

- (void)setState:(TableFooterState)state
{
    switch (state) {
        case TableFooterCellNormal:
            [indicatorView_ stopAnimating];
            [self setButtonTitle:BUTTON_NORMAL_TITLE];
            refreshButton_.userInteractionEnabled = YES;
            break;
            
        case TableFooterCellRefresh:
            [indicatorView_ startAnimating];
            [self setButtonTitle:BUTTON_REFRESH_TITLE];
            refreshButton_.userInteractionEnabled = NO;
            break;
            
        default:
            break;
    }
}

- (id)initWithFrame:(CGRect)frame BackgroundColor:(UIColor *)backgroundColor delegate:(id<TableFooterDelegate>)aDelegate
{
    self = [super initWithFrame:frame];
    
    if (self != nil) {
        
        // Configure the cell
        self.delegate = aDelegate;
        
        // Set the button
        refreshButton_ = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        refreshButton_.frame = CGRectMake(20.0f, 15.0f, 280.0f, 30.0f);
        [refreshButton_ addTarget:self action:@selector(refreshButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [refreshButton_ setTitle:@"获取更多信息" forState:UIControlStateNormal];
        [refreshButton_ setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self addSubview:refreshButton_];
        
        // Set the activity indicator view
        indicatorView_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        indicatorView_.frame = CGRectMake(85.0f, 20.0f, 20.0f, 20.0f);
        [self addSubview:indicatorView_];
        
        // Set the state
        [self setState:TableFooterCellNormal];
    }
    
    return self;
}


- (IBAction)refreshButtonPressed
{
    [delegate updatingWillStart];
    [self setState:TableFooterCellRefresh];
}

- (void)refreshDidFinished
{
    [self setState:TableFooterCellNormal];
}

- (void)dealloc
{
    refreshButton_ = nil;
    indicatorView_ = nil;
    
    [super dealloc];
}

@end
